<template>
  <div class="userinfo-container">
    <!-- 头部信息区域 -->
    <div class="userinfo-header bg-white p-6 rounded-md shadow-sm mb-4">
      <div class="flex items-start">
        <!-- 头像区域 - 红色圆圈位置 -->
        <div class="avatar-container mr-6">
          <el-avatar
            :size="100"
            :src="userAvatar"
            class="border-2 border-gray-200 cursor-pointer"
            @click="avatarDialogVisible = true"
            drag
          >
          </el-avatar>
        </div>

        <!-- 基本信息区域 -->
        <div class="info-container flex-1">
          <div class="grid grid-cols-2 gap-y-4">
            <div class="info-item">
              <span class="info-label text-gray-500">账号：</span>
              <span class="info-value">{{ userInfo.username }}</span>
            </div>

            <div class="info-item">
              <span class="info-label text-gray-500">姓名：</span>
              <span class="info-value">{{ userInfo.name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label text-gray-500">部门：</span>
              <span class="info-value">{{ deptName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label text-gray-500">性别：</span>
              <span class="info-value">{{
                userInfo.gender == 1 ? '男' : '女'
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label text-gray-500">手机号码：</span>
              <span class="info-value">{{
                maskPhoneNumber(userInfo.phone)
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label text-gray-500">身份证：</span>
              <span class="info-value">{{
                maskPhoneNumber(userInfo.idNum)
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 基本信息模块 -->
    <div class="bg-white p-6 rounded-md shadow-sm">
      <div class="section-header border-b pb-2 mb-6">
        <h2 class="text-lg font-medium">基本信息</h2>
      </div>

      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="100px"
        class="w-full max-w-3xl"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入账号"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="idNum">
          <el-input
            v-model="userForm.idNum"
            placeholder="请输入身份证号"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="部门" prop="deptId">
          <el-input v-model="deptName" placeholder="请输入账号" disabled>
          </el-input>
        </el-form-item>

        <el-form-item label="角色" prop="roleList">
          <el-select v-model="userForm.roles" placeholder="选择角色" :disabled="true" multiple>
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
              
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveUserInfo">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 头像修改对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="修改头像"
      width="460px"
      align-center
    >
      <div class="avatar-upload-container">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange"
          accept="image/jpeg,image/png,image/gif"
          :before-upload="beforeAvatarUpload"
        >
          <div class="avatar-preview-container">
            <img
              v-if="avatarPreview"
              :src="avatarPreview"
              class="avatar-preview"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
          <div class="avatar-upload-tip">
            <el-icon><InfoFilled /></el-icon>
            <span>点击或拖拽图片到此处上传</span>
          </div>
        </el-upload>

        <div class="avatar-upload-actions">
          <el-button
            type="primary"
            :disabled="!avatarFile"
            @click="uploadAvatar"
            >确认上传</el-button
          >
          <el-button @click="cancelAvatarUpload">取消</el-button>
        </div>

        <div class="avatar-upload-tips">
          <p>支持JPG、PNG、GIF格式，文件大小不超过2MB</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { uploadimg, uploadavatar } from '@/api/userInfo'
import { getuserbyid } from '@/api/usersManage.js'
import { getdeptlist } from '@/api/dept.js'
import { getrole } from '@/api/role.js'
import { updatauser } from '@/api/usersManage.js'
import { Plus, InfoFilled } from '@element-plus/icons-vue'

const userStore = useUserStore()

// 用户基本信息
const userInfo = userStore.userInfo
const userAvatar = computed(
  () =>
    userStore.userInfo?.avatar ||
    'https://api.dicebear.com/7.x/avataaars/svg?seed=student'
)
// 表单ref
const userFormRef = ref(null)
// 部门列表
const deptMapList = ref([])
// 角色列表
const rolesList = ref([])

// 部门名称
const deptName = computed(() => {
  return deptMapList.value.find((item) => item.id === userForm.deptId)?.deptName
})
// 角色名称
const roleName = computed(() => {
  return rolesList.value.find((item) => item.id === userForm.roleList)?.roleName
})

// 用户表单数据
const userForm = reactive({
  id: userInfo.id,
  username: userInfo.username || '',
  name: userInfo.name || '',
  phone: userInfo.phone || '',
  idNum: userInfo.idNum || '',
  gender: userInfo.gender || 1,
  deptId: userInfo.deptId || '',
  roles: userInfo.roles || [],
})

// 用户表单校验规则
const userFormRules = {
  username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  idNum: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      trigger: 'blur',
    },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
}

// 手机号码遮码显示
const maskPhoneNumber = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 头像上传相关
const avatarDialogVisible = ref(false)
const avatarFile = ref(null)
const avatarPreview = ref('')

// 处理头像选择变更
const handleAvatarChange = (file) => {
  // 保存文件引用
  avatarFile.value = file.raw

  // 生成本地预览
  avatarPreview.value = URL.createObjectURL(file.raw)
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  // 检查文件类型
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
    return false
  }

  // 检查文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  return true
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }

  // 显示加载中
  const loading = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', avatarFile.value)

    // 第一步：调用uploadimg上传图片获取src
    const { code, data, msg } = await uploadimg(formData)

    if (code !== 200) {
      throw new Error(msg || '上传图片失败')
    }

    // 获取到图片src
    const imgSrc = data

    // 第二步：使用获取到的src更新用户头像
    const updateRes = await uploadavatar({ avatar: imgSrc })

    if (updateRes.code !== 200) {
      throw new Error(updateRes.msg || '更新头像失败')
    }

    // 更新本地用户信息的头像
    userStore.getUserInfo()

    // 关闭对话框并更新成功提示
    ElMessage.success('头像更新成功')
    avatarDialogVisible.value = false

    // 刷新页面上的头像显示
    userInfo.avatar = userStore.userInfo.avatar
  } catch (error) {
    ElMessage.error(error.message || '头像上传失败')
  } finally {
    // 关闭加载
    loading.close()
  }
}

// 取消头像上传
const cancelAvatarUpload = () => {
  avatarFile.value = null
  avatarPreview.value = ''
  avatarDialogVisible.value = false
}

// 获取部门信息
const getDeptList = async () => {
  const { res, data } = await getdeptlist()
  const newMap = data.records.map((item) => {
    return { id: item.id, deptName: item.deptName }
  })
  deptMapList.value = newMap
}

// 根据id获取用户信息
const getUserById = async () => {
  const { code, data } = await getuserbyid(userInfo.id)
  if (code !== 200) {
    ElMessage.error('获取用户信息失败')
  }
  userForm.roles = data.roles
}

// 获取全部角色信息
const getRolesList = async () => {
  const { res, data } = await getrole({
    roleName: '',
    pageNum: 1,
    pageSize: 10,
  })
  const newRoles = data.records.map((item) => {
    return { id: item.id, deptName: item.roleName }
  })
  rolesList.value = newRoles
}

// 保存按钮
const saveUserInfo = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate(async (valid) => {
      if (valid) {
        const loading = ElLoading.service({
          lock: true,
          text: '保存中...',
          background: 'rgba(0, 0, 0, 0.7)',
        })

        try {
          // 此处应该调用API保存用户信息
          // const { data } = await updateUserInfoAPI(userForm)
          const { code, data } = await updatauser(userForm)

          // 更新本地用户信息
          // Object.assign(userInfo, userForm)

          ElMessage.success('用户信息保存成功')
        } catch (error) {
          console.error('保存用户信息失败:', error)
          ElMessage.error(error.message || '保存失败，请稍后重试')
        } finally {
          loading.close()
        }
      }
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  // 从用户信息中初始化表单数据
  if (userInfo) {
    userForm.username = userInfo.username || ''
    userForm.name = userInfo.name || ''
    userForm.phone = userInfo.phone || ''
    userForm.idNum = userInfo.idNum || ''
    userForm.gender = userInfo.gender || 1
    userForm.deptId = userInfo.deptId || ''
    userForm.roleList = userInfo.roleList || []
    userForm.email = userInfo.email || ''
    userForm.nickname = userInfo.nickname || ''
    userForm.address = userInfo.address || ''
    userForm.bio = userInfo.bio || ''
  }
  // 获取部门信息
  getDeptList()
  // 获取角色信息
  getRolesList()
  // 根据id获取用户信息
  getUserById()
})
</script>

<style lang="less" scoped>
.userinfo-container {
  .userinfo-header {
    .avatar-container {
      position: relative;
      min-width: 100px;
    }

    .info-item {
      margin-bottom: 8px;

      .info-label {
        display: inline-block;
        min-width: 80px;
      }

      .info-value {
        font-weight: 500;
      }
    }
  }
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
  width: 100%;

  .avatar-preview-container {
    width: 200px;
    height: 200px;
    margin: 0 auto 20px;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  .avatar-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }

  .avatar-upload-tip {
    color: #606266;
    font-size: 14px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
  }
}

/* 修复上传区域和提示文本的水平对齐问题 */
:deep(.el-upload) {
  width: 100%;
  display: flex !important;
  flex-direction: column !important;
  align-items: center !important;
}

:deep(.el-upload-dragger) {
  width: 200px;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-upload-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: center;
}

.avatar-upload-tips {
  margin-top: 15px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}
</style>
